package org.gateway.interceptors;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.gateway.pojo.ErrorResponse;
import org.gateway.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static org.gateway.util.StaticVariable.User_Jwt;

@Component
public class jwtGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 在类中添加 AntPathMatcher 实例
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private static final List<String> AUTH_PUBLIC = Arrays.asList(
            "/user/login",
            "/user/register",
            "/exhibition",
            "/exhibition/\\d+",
            "/exhibition/isLikeExhibition/\\d+",
            "/exhibition/getExhibitionIdByName/**",
            "/search/**",
            "/collection/isLikeCollection/\\d+",
            "/collection/getOneCollection/**"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request =  exchange.getRequest();
        // 检查是否匹配免认证路径
        if (isPublicPath(request.getPath().toString())) {
            // 放行
            return chain.filter(exchange);
        }
        List<String> authorization = request.getHeaders().get("Authorization");
        String token;
        //判断是否有token
        if (authorization != null && !authorization.isEmpty()) {
           token = authorization.getFirst();
        } else {
            token = null;
        }
        //校验 token
        try {
            //在redis中查询看看是否是最新的token
            if(!JwtUtils.validateJwt(token)){
                //拦截设置状态码为401
                return handleUnauthorized(exchange, "Token已过期");
            }
            //获取手机号
            String phone = JwtUtils.getJwtUsername( token);
            if(!Objects.equals(stringRedisTemplate.opsForValue().get(User_Jwt + phone), token)){
                //判断用户传的token是不是最新的
                return handleUnauthorized(exchange, "用户已过期");
            }
            //重置token的过期时间
            stringRedisTemplate.expire(User_Jwt + phone, 30, TimeUnit.MINUTES);
        } catch (Exception e) {
            //拦截设置状态码为401
            return handleUnauthorized(exchange, "用户已过期");
        }
        //在请求头里设置token
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder -> builder.header("Authorization", token))
                .build();
        return chain.filter(newExchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
    private boolean isPublicPath(String requestPath) {
        System.out.println(requestPath);
        // 1. 检查精确匹配
        if (AUTH_PUBLIC.contains(requestPath)) {
            return true;
        }

        // 2. 检查 Ant 风格通配符匹配
        for (String pattern : AUTH_PUBLIC) {
            if (antPathMatcher.match(pattern, requestPath)) {
                return true;
            }
        }

        // 2. 检查正则匹配
        for (String pattern : AUTH_PUBLIC) {
            if (pattern.contains("\\")) { // 检测正则表达式
                if (requestPath.matches(pattern)) {
                    return true;
                }
            }
        }

        return false;
    }
    // 处理未授权的请求
    public Mono<Void> handleUnauthorized(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatusCode.valueOf(200));
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        // 创建错误响应对象
        ErrorResponse error = new ErrorResponse(401, message);

        try {
            // 使用 Jackson 序列化为 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResponse = objectMapper.writeValueAsString(error);

            byte[] bytes = jsonResponse.getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);

            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            // 处理 JSON 序列化错误
            return Mono.error(e);
        }
    }

}
